package org.simtube.index;

import java.util.Arrays;
import java.util.Random;

import org.simtube.util.CosineComparator;
import org.simtube.util.DocItem;
import org.simtube.util.DocVector;

public class QuickIndex implements Index {

	private DocItem[] docMat;
	private int docCount;
	
	/**
	 * Return the number of rows in this document-matrix
	 * @return The number of rows (documents)
	 */
	public int getDocCount() {
		return this.docCount;
	}
	
	/**
	 * Default constructor, initialize the doc matrix
	 * @param docMat The document vector matrix
	 */
	public QuickIndex(DocItem[] docMat) {
		this.setDocMat(docMat);
		docCount = docMat.length;
	}
	
	@Override
	public void buildIndex() {
	}

	@Override
	public void loadIndex(String indexFile) {
	}
	
	@Override
	public int[] kNNQuery(int k, DocVector query) {
		
		if(k > docCount) {
			System.out.println("You are requesting too many results... [QuickIndex.java]");
			return null;
		}
		
		// DocItem[] nDocMat = docMat.clone();
		
		Arrays.sort(docMat, new CosineComparator(query));
		
		int[] dlist = new int[k];

		for(int i = 0; i < k; i++) dlist[i] = docCount - i - 1;
		
		return dlist;
	}
	
	@Override
	public void setDocMat(DocItem[] docMat) {
		this.docMat = docMat;
		this.docCount = docMat.length;
	}
	
	public static void main(String[] args) {
		
		DocItem[] docMat = new DocItem[10];
		Random r = new Random();
		for(int i = 0; i < 10; i++) {
			double[] v = new double[2];
			v[0] = r.nextDouble();
			v[1] = r.nextDouble();
			
			docMat[i] = new DocItem(new DocVector(v).normalize(), i);
			System.out.println(docMat[i]);
		}
		
		DocVector query;
		double[] vq = new double[2];
		vq[0] = r.nextDouble();
		vq[1] = r.nextDouble();
		
		query = new DocVector(vq);
		System.out.println("Query: " + query);
		
		QuickIndex qindex = new QuickIndex(docMat);
		
		int[] ilist = qindex.kNNQuery(5, query);
		
		for(int i = 0; i < ilist.length; i++) {
			DocVector v = docMat[ilist[i]].vector;
			System.out.println(docMat[ilist[i]] + ", product: " + v.multiply(query));
		}
	}
}
